package com.linkage.seapeak.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.user.ImageShowActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.CommonUtils;
import com.linkage.seapeak.utils.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultDisposable;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

public abstract class BaseFragment extends Fragment {

    private ShapeLoadingDialog shapeLoadingDialog;




    public int dp2px(float dp) {
        return CommonUtils.dp2px(getActivity(), dp);
    }

    public void showToast(String msg) {
        ToastUtil.getInstance(getActivity()).showShortToast(msg);
    }

    private String phone;

    public void SetPhone(String p)
    {
        phone = p;
    }

    public void showToast(String msg, ToastUtil.TOAST_TYPE toast_type) {
        ToastUtil.getInstance(getActivity()).showToast(msg, toast_type);
    }

    public void showProgress() {
        shapeLoadingDialog = new ShapeLoadingDialog(getActivity());
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
    }

    public void hideProgress() {
        if (shapeLoadingDialog!= null && shapeLoadingDialog.getDialog().isShowing())
            shapeLoadingDialog.dismiss();
    }

    protected String getUserToken(){
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        return userToken;
    }


    public static final int TYPE_EDIT = 1;
    public static final int TYPE_PREVIEW = 2;


    public void imageSizeChange(int size) {

    }

    public void imageSizeChange(int tag, int size) {

    }

    public static class GridImagesAdapter extends RecyclerView.Adapter<GridImagesAdapter.ViewHolder> {
        private List<UploadImage> list = new ArrayList<>();
        private int mType; // 1-编辑，2-预览
        private WeakReference<Activity> mWeekRefContext;

        private int maxSize = 27;
        private int maxOnce = 9;

        public GridImagesAdapter(Activity baseCreateActivityWeakReference, int type) {
            this.mWeekRefContext = new WeakReference<>(baseCreateActivityWeakReference);
            mType = type;
        }


        public void setSelectMax(int selectMax) {
            this.maxSize = selectMax;
        }


        public void setList(List<UploadImage> list) {
            this.list = list;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            ImageView mImg;
            LinearLayout ll_del;
            TextView tv_duration;

            public ViewHolder(View view) {
                super(view);
                mImg = view.findViewById(R.id.fiv);
                ll_del = view.findViewById(R.id.ll_del);
            }
        }

        public void setTag(int tag) {
            //this.tag = tag;
        }

        @Override
        public int getItemCount() {
            // 预览模式
            if (mType == TYPE_PREVIEW) {
                return list.size();
            }
            // 这里+1，用作最后的添加图片
            return Math.min(maxSize, list.size() + 1);
        }

        @Override
        public int getItemViewType(int position) {
            return mType;
        }

        @Override
        public GridImagesAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            Context context = mWeekRefContext.get();
            View view = View.inflate(context, R.layout.item_filter_image, null);
            GridImagesAdapter.ViewHolder viewHolder = new GridImagesAdapter.ViewHolder(view);
//            if (viewType == TYPE_PREVIEW) {
            viewHolder.ll_del.setVisibility(View.GONE);
//            }
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final GridImagesAdapter.ViewHolder viewHolder, final int position) {
            //
            if (position == list.size()) {
                viewHolder.ll_del.setVisibility(View.GONE);
                viewHolder.mImg.setImageResource(R.drawable.ic_img_add);
                viewHolder.mImg.setScaleType(ImageView.ScaleType.FIT_XY);
                viewHolder.mImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        BaseCreateActivity baseCreateActivity = mWeekRefContext.get();
//                        if (baseCreateActivity != null) pickAndUploadPic(list, GridImagesAdapter.this);
                    }
                });
                return;
            }

            viewHolder.ll_del.setVisibility(View.GONE);
            String url = list.get(position).getLoadUrl();
            viewHolder.ll_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int index = viewHolder.getAdapterPosition();
                    // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
                    // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
                    if (index != RecyclerView.NO_POSITION) {
                        list.remove(index);
                        // EventBus.getDefault().post(new MovePicEvent(index + ""));
                        notifyItemRemoved(index);
                        notifyItemRangeChanged(index, list.size());
                    }
                }
            });

            viewHolder.mImg.setScaleType(ImageView.ScaleType.FIT_CENTER);
            if (mWeekRefContext.get().isFinishing()) {
                return;
            }
            Glide.with(mWeekRefContext.get())
                    .load(url)
                    .placeholder(R.mipmap.ic_launcher)
                    .into(viewHolder.mImg);

            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    int adapterPosition = viewHolder.getAdapterPosition();
//                    ImageShowActivity.start(mWeekRefContext.get(), (ArrayList) list, adapterPosition,
//                            mType == TYPE_EDIT ? ImageShowActivity.FROM_MUlTI_EDIT : ImageShowActivity.FROM_MUlTI_SHOW);
                }
            });
        }
    }

    public static final int REQUEST_CALL_PERMISSION = 10111; //拨号请求码
    public static final int REQUEST_SMS_PERMISSION = 10112; //拨号请求码

    /**
     * 判断是否有某项权限
     * @param string_permission 权限
     * @param request_code 请求码
     * @return
     */
    public boolean checkReadPermission(String string_permission,int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(getActivity(), string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{string_permission}, request_code);
        }
        return flag;
    }

    /**
     * 检查权限后的回调
     * @param requestCode 请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CALL_PERMISSION: //拨打电话
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(getActivity(),"请允许拨号权限后再试",Toast.LENGTH_SHORT).show();
                } else {//成功
//                    call("tel:"+"10086");
                    Intent intent1 = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent1.setData(data);
                    startActivity(intent1);

                }
                break;
            case REQUEST_SMS_PERMISSION:
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(getActivity(),"请允许拨号权限后再试",Toast.LENGTH_SHORT).show();
                } else {//成功
//                    call("tel:"+"10086");
                    Intent intent1 = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent1.setData(data);
                    startActivity(intent1);

                }
                break;
        }
    }
}
